package it.intecs.pisa.smarcos.receivers;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.XMLParser;
import it.intecs.pisa.smarcos.sounds.SoundEffects;
import it.intecs.pisa.smarcos.util.ContextUtils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSReceivedBroadcastReceiver extends BroadcastReceiver {
	private static final String TAG = SMSReceivedBroadcastReceiver.class.getSimpleName();
	
	private ContextUtils cUtils;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		Log.d(TAG, "SMSReceivedBroadcastReceiver - onReceive");
		
		cUtils = new ContextUtils(context);
		
		Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        
        SoundEffects soundEff=SoundEffects.getInstance(context);
        soundEff.beep();
        
        XMLParser menuMan=XMLParser.getInstance(null,null);
		
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); 
                
                String name = cUtils.retriveContactFromNumber( msgs[i].getOriginatingAddress());
                if (name == null)
                	menuMan.addNotification(context.getString(R.string.MV_Notification_SMS), context.getString(R.string.MV_Notification_SMS_Msg) 
                			+ "\n" + msgs[i].getOriginatingAddress());
                else
                	menuMan.addNotification(context.getString(R.string.MV_Notification_SMS), context.getString(R.string.MV_Notification_SMS_Msg) 
                			+ "\n" + name);
            }
         }    
	}
}
